package com.dynamic.mybatis.web.mvc;

import com.dynamic.mybatis.core.intercept.DynamicMappedStatementHandler;
import com.dynamic.mybatis.core.metadata.DynamicMappedStatement;
import com.dynamic.mybatis.core.utils.CollectionUtils;
import com.dynamic.mybatis.core.utils.StringUtils;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class MappedStatementRequestMappingRegister implements DynamicMappedStatementHandler {
    private static final Log logger = LogFactory.getLog(MappedStatementRequestMappingRegister.class);
    @Autowired
    private RequestMappingHandlerMapping requestMappingHandlerMapping;
    @Autowired
    private MappedStatementRequestExecuteHandler mappedStatementRequestExecuteHandler;

    Method executePostMethod;
    Method executeGetMethod;
    Method executeMethod;

    public MappedStatementRequestMappingRegister() {
        for (Method method : MappedStatementRequestExecuteHandler.class.getMethods()) {
            String methodName = method.getName();
            if ("executePost".equals(methodName)) {
                executePostMethod = method;
            } else if ("executeGet".equals(methodName)) {
                executeGetMethod = method;
            } else if ("execute".equals(methodName)) {
                executeMethod = method;
            }
        }
    }


    public void registerMapping(OPERATE operate, List<DynamicMappedStatement> dmsList) {
        if(CollectionUtils.isEmpty(dmsList)){
            return;
        }
         dmsList = dmsList.stream().filter(dms -> dms.isRest() && dms.isEnable()).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(dmsList)){
            return;
        }
        logger.warn("register spring mvc "+String.format("%-10s","{mthods}")+" /{tenantCode}/{namespace}/{code}");
        for(DynamicMappedStatement dms : dmsList){
            registerMapping(operate,dms);
        }
    }


    public void registerMapping(OPERATE operate, DynamicMappedStatement dms) {
        if (StringUtils.isBlank(dms)) {
            return;
        }
        String path = dms.getId().replaceAll("\\.", "/");
        // String path = prefix+"/{mappedStatementId}";

        RequestMappingInfo.Builder requestBuilder = RequestMappingInfo.paths(path);
        if (StringUtils.isNotBlank(dms.getMethod())) {
            requestBuilder.methods(RequestMethod.valueOf(dms.getMethod().method()));
        }
        RequestMappingInfo requestMappingInfo = requestBuilder.build();
        requestMappingHandlerMapping.unregisterMapping(requestMappingInfo);
        if (operate != OPERATE.DELETE && dms.isRest() && dms.isEnable()) {
            requestMappingHandlerMapping.registerMapping(requestMappingInfo, mappedStatementRequestExecuteHandler, executeMethod);
            String metods = requestMappingInfo.getMethodsCondition().getMethods().stream().map(RequestMethod::toString).collect(Collectors.joining());
            logger.warn("register spring mvc "+String.format("%-10s",metods)+"  "+path);
        }
    }

    @Override
    public void before(OPERATE operate, DynamicMappedStatement dms) {

    }

    @Override
    public void after(OPERATE operate, DynamicMappedStatement dms) {
        registerMapping(operate, dms);
    }
}
